import PhotoSwipe from 'photoswipe';
import 'photoswipe/style.css';
import CustomEventEmitter from './customEventEmitter';

const defaultOptions = {
    videoAttributes: { controls: '', playsinline: '', preload: 'auto', muted: false, volume: 1 }, // 视频默认属性
    autoplay: true, // 自动播放

    // 防止在视频底部拖动/滑动手势
    // 设置为0以禁用
    preventDragOffset: 40
};

/**
 * 检查幻灯片是否包含视频内容
 *
 * @param {Slide|Content} content 幻灯片或内容对象
 * @returns Boolean
 */
function isVideo(content) {
    return content && content.data && content.data.type === 'video';
}

class PhotoSwipeVideo {
    constructor(pswp, options = {}) {
        this.pswp = pswp;
        this.options = Object.assign(defaultOptions, options);

        this.pswp.eventEmitter = new CustomEventEmitter();

        this.pswp.on('contentLoad', this.onContentLoad.bind(this));
        this.pswp.on('contentActivate', this.onContentActivate.bind(this));
        this.pswp.on('contentDeactivate', this.onContentDeactivate.bind(this));
        this.pswp.on('contentDestroy', this.onContentDestroy.bind(this));
        this.pswp.on('contentAppend', this.onContentAppend.bind(this));
        this.pswp.on('close', this.onClose.bind(this));
    }

    onContentLoad(e) {
        const content = e.content;
        if (!isVideo(content)) return;
        e.preventDefault();
        content.state = 'loading';

        const video = document.createElement('video');
        Object.keys(this.options.videoAttributes).forEach(attr => {
            video.setAttribute(attr, this.options.videoAttributes[attr]);
        });
        video.volume = this.options.videoAttributes.volume;
        video.style.position = 'absolute';
        video.style.left = 0;
        video.style.top = 0;
        video.style.width = '100%';
        video.style.height = '100%';

        if (content.data.videoSources) {
            content.data.videoSources.forEach(source => {
                const sourceEl = document.createElement('source');
                sourceEl.src = source.src;
                sourceEl.type = source.type;
                video.appendChild(sourceEl);
            });
        } else if (content.data.src) {
            video.src = content.data.src;
        }

        if (content.data.poster) {
            video.setAttribute('poster', content.data.poster);
        }

        video.addEventListener('canplay', () => {
            content.state = 'loaded';
        });

        content.element = video;
    }

    onContentActivate({ content }) {
        const that = this;
        if (isVideo(content) && this.options.autoplay) {
            content.element.currentTime = 0;
            const playPromise = content.element.play();
            if (playPromise !== undefined) {
                playPromise.catch(error => {
                    console.warn('自动播放失败，可能需要用户交互:', error);
                });
            }
            if (!content.hasEndedListener) {
                content.element.addEventListener('ended', () => {
                    that.pswp.eventEmitter.dispatch('videoEnded');
                });
                content.hasEndedListener = true; // 更新标记，避免重复添加监听器
            }
        }

        const timer = setTimeout(() => {
            clearTimeout(timer);
            that.pswp.eventEmitter.dispatch('contentActivate', { content })
        },10);
    }

    onContentDeactivate({ content }) {
        if (isVideo(content)) {
            content.element.pause();
            if (content.hasEndedListener) {
                content.element.removeEventListener('ended', () => {
                    this.pswp.eventEmitter.dispatch('videoEnded');
                });
                content.hasEndedListener = false; // 更新标记
            }
        }
    }

    onContentDestroy({ content }) {
        if (isVideo(content)) {
            content.element.pause();
            content.element.src = '';
            content.element.remove();
            if (content.hasEndedListener) {
                content.element.removeEventListener('ended', () => {
                    this.pswp.eventEmitter.dispatch('videoEnded');
                });
                content.hasEndedListener = false;
            }
            content.element = null;
        }
    }

    onContentAppend(e) {
        if (isVideo(e.content)) {
            e.preventDefault();
            e.content.isAttached = true;

            // **确保 `slide.container` 存在后再附加 video**
            if (e.content.slide && e.content.slide.container) {
                e.content.slide.container.appendChild(e.content.element);
            } else {
                console.warn("Slide container 不存在，可能导致视频无法附加");
            }
        }
    }

    onClose() {
        if(!this.pswp.getSlides)return
        this.pswp.getSlides().forEach(slide => {
            if (isVideo(slide.content)) {
                slide.content.element.pause();
                slide.content.element.src = '';
                slide.content.element.remove();
            }
        });
    }
}

function openPhotoSwipe(items, options = {}) {
    const pswp = new PhotoSwipe({
        dataSource: items,
        ...options
    });

    new PhotoSwipeVideo(pswp, options.videoOptions || {});
    pswp.init();
    return pswp;
}

export default openPhotoSwipe;